package com.system.service.sysuser.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.core.constants.HttpConstants;
import com.common.core.domain.LoginUser;
import com.common.core.domain.Result;
import com.common.core.domain.vo.LoginUserVO;
import com.common.core.enums.ResultCode;
import com.common.core.enums.UserIdentity;
import com.common.security.exception.ServiceException;
import com.common.security.service.TokenService;
import com.system.domain.sysuser.SysUser;
import com.system.domain.sysuser.dto.SysUserSaveDTO;
import com.system.mapper.sysuser.SysUserMapper;
import com.system.service.sysuser.SysUserService;
import com.system.utils.BCryptUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


@Slf4j
@Service
@RefreshScope
public class SysUserServiceImpl implements SysUserService {
    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    @Override   //用户校验管理员登录
    public Result<String> login(String userAccount, String password) {
        //校验用户名或密码是否为空
        if(!StringUtils.hasLength(userAccount) || !StringUtils.hasLength(password)){
            return Result.fail(114514,"用户名或密码为空");
        }
        LambdaQueryWrapper<SysUser> sysUserQueryWrapper=new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(sysUserQueryWrapper
                .select(SysUser::getUserId,SysUser::getPassword,SysUser::getNickName)
                .eq(SysUser::getUserAccount, userAccount));

        if(sysUser==null){
            //用户不存在
            return Result.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if(!BCryptUtils.matchesPassword(password,sysUser.getPassword())){
            //密码错误
            return Result.fail(ResultCode.FAILED_LOGIN);
        }
        //匹配成功
        return Result.success(tokenService.createToken(sysUser.getUserId(),
                secret, UserIdentity.ADMIN.getValue(),sysUser.getNickName(),null));
    }

    @Override
    public int add(SysUserSaveDTO sysUserSaveDTO) {
        SysUser tem = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));
        if(tem!=null){
            //说明已经有这个管理员了
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }
        SysUser sysUser=new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
        return sysUserMapper.insert(sysUser);
    }

    @Override
    public Result<LoginUserVO> info(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }

        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        //log.info("获取到token:{}",secret);
        if(loginUser==null){
            return Result.fail();
        }

        LoginUserVO loginUserVO=new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return Result.success(loginUserVO);
    }

    @Override
    public boolean logout(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return tokenService.deleteLoginUser(token,secret);
    }
}